<?php

namespace App\Http\Controllers\Admin;

use App\Models\MemberOther;
use App\Models\NewAdmin;
use App\Models\Order;

use App\Models\OrderBuyoutAudit;
use App\Models\OrderGoods;
use App\Models\OrderLease;
use App\Models\OrderLeaseAudit;

use App\Models\OrderLeasePartial;
use App\Models\OrderLeasePartRemark;
use App\Models\OrderRemark;
use App\Models\OtherWithholdLog;
use App\Models\ShopSms;
use App\Models\ShopTrans;
use App\Models\YifubaoPay;
use App\Services\AlipayService;
use App\Services\AntchainAtoService;
use App\Services\AntchainService;
use App\Services\AuthService;
use App\Services\ChargeService;
use App\Services\CommonService;
use App\Services\CreditCallService;
use App\Services\GoodsService;
use App\Services\OrderService;
use App\Services\SmsService;
use App\Services\SuningPayService;
use App\Services\WechatService;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;

class OrderLeaseController extends BaseController
{

    /**
     * 提前支付审核
     */
    public function orderLeaseAuditList(Request $request){
        $request_data = $request->all();
        $list = (new OrderLeaseAudit)->checkList($request_data);

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$list);
    }


    /**
     * 提前手动支付
     */
    public function submitLeasePay(Request $request){
        $dataAudit=OrderLeaseAudit::find($request['id'])->toArray();
        if(empty($dataAudit)||$dataAudit['check_status']['value']){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'记录不存在或已审核');
        }
        if($dataAudit['check_status']['value']>0){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'记录已审核');
        }

        if(empty($dataAudit['order_id'])||empty($dataAudit['lease_id'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
        }

        $userToken = $request->header("Authorization");
        $user = NewAdmin::where(['token'=>$userToken,'type'=>AuthService::MODEL_ADMIN])->first();
        $user = obToArray($user);

        if(md5($user['mobile'].$request['password']) != $user['password']){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'密码输入错误错误');
        }

        $order = Order::from('sp_order_2 as o')->where('o.id',$dataAudit['order_id'])
            ->select(
                'o.id','o.flow_id','o.sign_status','o.pact_url','o.sign_no','o.withhold_status','o.trade_no','o.month_total'
            )
            ->first();
        $order = $order ? $order->toArray() : [];

        if(empty($order)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
        }
        if ($order['sign_status']!=2||empty($order['pact_url'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'该订单未签约合同');
        }
        if ($order['sign_no']&&empty($order['withhold_status'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'未签署代扣租赁宝');
        }


        $OrderLease= OrderLease::where('id',$dataAudit['lease_id'])->where('order_id',$dataAudit['order_id'])
            ->select(
                'id','which_period','rent','status'
            )
            ->first();
        $OrderLease = $OrderLease ? $OrderLease->toArray() : [];
        if(empty($OrderLease)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
        }
        if($OrderLease['status']==1&&!empty($OrderLease['pay_time'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'该期已支付');
        }

        if($request['check']==OrderLeaseAudit::CHECK_STATUS_AUDIT){
//            $res=WechatService::getFundFlow(trim($dataAudit['transaction_id']),$OrderLease['rent']);
//            if(!$res){
//                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'未查询到支付流水单号');
//            }
            DB::beginTransaction();
            if($OrderLease['which_period']==1){
                Order::where(['id' => $order['id']])->update(['status'=>OrderService::ORDER_STATUS_PAY_SUCCESS]);
            }
            $successPayToOrderLease=OrderLease::successPayToOrderLease($dataAudit['order_id'],$dataAudit['lease_id'],$OrderLease['rent']);
            if(!$successPayToOrderLease){
                DB::rollBack();
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'更改失败');
            }
            $resRule = AntchainService::payRule($order['flow_id']);
            $resRule=json_decode($resRule['data'],true);

            $key=$OrderLease['which_period']-1;
            OrderLeaseAudit::where('id',$request['id'])->update(['check_status'=>1,'operator_id'=>$user['id']]);

            if($order['sign_no']){
                $res =  AntchainAtoService::repayWithholdPlan($order['trade_no'],$OrderLease['which_period'],$OrderLease['rent']);
            }else{
                $res = AntchainService::paysingletradeCancel($order['flow_id'],$resRule['payRules'][$key]['outTradeNo']); //取消智能合同某一期代扣条目
            }
            if($res){

                DB::commit();
                //检测逾期订单状态
                $status = Order::checkOrderOverdueStatus($dataAudit['order_id']);
                if($status){
                    Order::where(['id' => $order['id']])->update(['status'=>$status]);
                    CreditCallService::repayInvestData($order['id'],$OrderLease['id']);//上报征信-还款
                }
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'确认提前支付成功');
            }else{
                DB::rollBack();
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'更改失败');
            }
        }

        if($request['check']==OrderLeaseAudit::CHECK_STATUS_REJECT){
            $res=OrderLeaseAudit::where('id',$request['id'])->update(['check_status'=>2,'check_reason'=>$request['check_reason'],'operator_id'=>$user['id']]);
            if($res){
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'审核成功');
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'审核失败');
            }
        }


    }


    /**
     * 审核通过或拒绝买断价结算
     */
    public function submitOrderBuyoutCheck(Request $request){
        $dataAudit=OrderBuyoutAudit::find($request['id'])->toArray();
        if(empty($dataAudit)||$dataAudit['check_status']['value']){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'记录不存在或已审核');
        }
        if($dataAudit['check_status']['value']>0){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'记录已审核');
        }

        if(empty($dataAudit['order_id'])||(empty($dataAudit['amount'])&&empty($dataAudit['reduced_amount']))){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
        }

        $userToken = $request->header("Authorization");
        $user = NewAdmin::where(['token'=>$userToken,'type'=>AuthService::MODEL_ADMIN])->first();
        $user = obToArray($user);

        if(md5($user['mobile'].$request['password']) != $user['password']){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'密码输入错误错误');
        }

        $order = Order::from('sp_order_2 as o')->where('o.id',$dataAudit['order_id'])
            ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
            ->select(
                'o.id','o.id as order_id','o.flow_id','o.status','o.uid','o.seller_id','og.goods_id','o.order_from','o.sign_no','o.trade_no'
            )
            ->first();
        $order = $order ? $order->toArray() : [];
        if(empty($order)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
        }
        if(!in_array($order['status'],['30','38','39','42','60'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单当前状态不支持审核');
        }

        if($request['check']==OrderBuyoutAudit::CHECK_STATUS_AUDIT&&$dataAudit['amount']>0){
            DB::beginTransaction();

            OrderBuyoutAudit::where('id',$request['id'])->update(['check_status'=>1,'operator_id'=>$user['id']]);
            Order::from('sp_order_2 as o')->where('o.id',$dataAudit['order_id'])->update(['reduced_status'=>1,'reduced_price'=>$dataAudit['amount']]);

            if(MemberOther::where('id',$order['uid'])->value('user_id')){
                $res = AntchainService::paytradeCancel($order['flow_id']); //取消智能合同某一期代扣条目
            }

            if(!empty($order)){
                $settle_data = ShopTrans::getSettleData($order);
                if(empty($settle_data)){
                    DB::rollBack();
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单来源费率未设置');
                }
                if(!empty($settle_data)){
                    unset($settle_data['trans_detail']['insure_rate']);

                    $order=array_merge($order,$settle_data['trans_detail']);
                    $settle_amount=$dataAudit['amount'];
                    if ($settle_data['is_preposition'] == 1) {
                        $service_fee = bcmul($settle_amount , $settle_data['post_deduction'] * 0.01,2);
                        $settle_amount = sprintf("%.4f", $settle_amount - $service_fee);
                        $remarks = '结算价买断剩余租金';
                        $settle_data['trans_detail']['platform_amount'] = 0;
                        $settle_data['trans_detail']['insurance_amount'] = 0;
                        $settle_data['trans_detail']['insurance_amount'] = 0;
                        $settle_data['trans_detail']['file_amount'] = 0;
                        $settle_data['trans_detail']['withhold_amount'] = 0;

                        $res = ShopTrans::addOrderTrans($order, $settle_amount, $service_fee, '', $remarks, 0, $settle_data['fee_rate'], $settle_data['fixed_fee'], $settle_data['trans_detail'], ShopTrans::ORDER_TRANS_TYPE_SETTLE);
                        if ($res) {
                            DB::commit();
                            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '结算成功2');
                        } else {
                            DB::rollBack();
                            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '结算失败2');
                        }
                    } else {
                        $service_fee = sprintf("%.4f", $settle_amount * $settle_data['fee_rate'] * 0.01 + $settle_data['fixed_fee']);
                        $settle_amount = sprintf("%.4f", $settle_amount - $service_fee);
                        $remarks = '结算价买断剩余租金';
                        $settle_data['trans_detail']['platform_amount'] = sprintf("%.4f", $settle_amount * $settle_data['trans_detail']['platform_rate'] * 0.01);
                        $settle_data['trans_detail']['insurance_amount'] = sprintf("%.4f", $settle_amount * $settle_data['trans_detail']['insurance_rate'] * 0.01);
                        $settle_data['trans_detail']['insurance_amount'] = sprintf("%.4f", $settle_amount * $settle_data['trans_detail']['financing_rate'] * 0.01);
                        $settle_data['trans_detail']['file_amount'] = sprintf("%.4f", $settle_amount * $settle_data['trans_detail']['file_rate'] * 0.01);
                        $settle_data['trans_detail']['withhold_amount'] = sprintf("%.4f", $settle_amount * $settle_data['trans_detail']['withhold_rate'] * 0.01);

                        $res = ShopTrans::addOrderTrans($order, $settle_amount, $service_fee, $order['alipay_trade_no'], $remarks, 0, $settle_data['fee_rate'], $settle_data['fixed_fee'], $settle_data['trans_detail'], ShopTrans::ORDER_TRANS_TYPE_SETTLE);
                        if ($res) {
                            DB::commit();
                            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '审核成功');
                        } else {
                            DB::rollBack();
                            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '结算失败4');
                        }
                    }

                } else {
                    DB::rollBack();
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '结算失败5！');
                }
            } else {
                DB::rollBack();
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        }else if($request['check']==OrderBuyoutAudit::CHECK_STATUS_AUDIT&&$dataAudit['reduced_amount']>0){
            $one=OrderLease::where('order_id',$order['id'])->where('status','<>',OrderLease::ORDER_LEASE_STATUS_PAID)->first();
            if($one){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'账单用户未支付完成');
            }
            DB::beginTransaction();

            OrderBuyoutAudit::where('id',$request['id'])->update(['check_status'=>1,'operator_id'=>$user['id']]);
            Order::from('sp_order_2 as o')->where('o.id',$dataAudit['order_id'])->update(['reduced_status'=>2,'reduced_price'=>$dataAudit['reduced_amount']]);

            if($order['sign_no']){
                AntchainAtoService::cancelWithholdPlan($order['trade_no']);
            }
            if(MemberOther::where('id',$order['uid'])->value('user_id')&&!$order['flow_id']){
                AntchainService::paytradeCancel($order['flow_id']); //取消智能合同某一期代扣条目
            }
            $OrderLease=OrderLease::where('order_id',$order['id'])->where('status',OrderLease::ORDER_LEASE_STATUS_PAID)->limit(2)->orderBy('id','desc')->get()->toArray();
            $reduced_amount=$dataAudit['reduced_amount'];
            foreach ($OrderLease as $k=>$v){
                $dataAudit['reduced_amount']=$v['paid_rent']-$dataAudit['reduced_amount'];
                $res=OrderLease::where('id',$v['id'])->update(['paid_rent'=>$dataAudit['reduced_amount']>0?$dataAudit['reduced_amount']:0]);
                if($k==0){
                    $order_trans = ShopTrans::getOrderRefundTrans($order,$v);
                    if($res&&$v['settle_type'] == OrderLease::ORDER_LEASE_SETTLE_STATUS_YES){
                        $res=ShopTrans::addOrderTrans($order,$reduced_amount,$order_trans['service_fee'],$v['out_order_no'],'结算价买断，优惠金额',$v['id'],$order_trans['fee_rate'],$order_trans['fixed_fee'],$order_trans['trans_detail'],ShopTrans::ORDER_TRANS_TYPE_REFUND);
                    }
                }
                if($dataAudit['reduced_amount']>=0){
                    break;
                }
                $dataAudit['reduced_amount']=abs($dataAudit['reduced_amount']);
            }



            if(!empty($res)){
                DB::commit();
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '审核成功');
            } else {
                DB::rollBack();
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
            }
        }



        if($request['check']==OrderBuyoutAudit::CHECK_STATUS_REJECT){
            $res=OrderBuyoutAudit::where('id',$request['id'])->update(['check_status'=>2,'check_reason'=>$request['check_reason'],'operator_id'=>$user['id']]);
            if($res){
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'审核成功');
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'审核失败');
            }
        }

    }


    /**
     * 结算价买断审核
     */
    public function orderBuyoutAuditList(Request $request){
        $request_data = $request->all();
        $list = (new OrderBuyoutAudit())->checkList($request_data);

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$list);
    }



    /**
     * 提前手动支付提交申请
     */
    public function submitLeasePayApply(Request $request){
        if(empty($request['orderId'])||empty($request['leaseId'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
        }

        $userToken = $request->header("Authorization");
        $user = NewAdmin::where(['token'=>$userToken,'type'=>AuthService::MODEL_ADMIN])->first();
        $user = obToArray($user);

        if(md5($user['mobile'].$request['password']) != $user['password']){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'密码输入错误错误');
        }
        if(empty($request['transaction_id'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请上传交易单号');
        }
        if(strlen($request['transaction_id'])!=28&&strlen($request['transaction_id'])<32){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'交易单号有误');
        }
        $id=OrderLeaseAudit::where('transaction_id',$request['transaction_id'])->where('check_status',1)->value('id');
        if($id){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'该交易单号已存在');
        }

        if(empty($request['image_path'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请上传交易图片');
        }

        $order = Order::from('sp_order_2 as o')->where('o.id',$request['orderId'])
            ->select(
                'o.id','o.uid','o.flow_id','o.sign_status','o.pact_url','o.trade_no','o.month_total'
            )
            ->first();
        $order = $order ? $order->toArray() : [];

        $cert_name=MemberOther::where('id',$order['uid'])->value('cert_name');

        if(strpos($request['remark'],$cert_name)===false){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'备注信息中需包含用户姓名,请确认订单信息与账单信息是否一致');
        }
        if(empty($order)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
        }
        if ($order['sign_status']!=2||empty($order['pact_url'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'该订单未签约合同');
        }

        $leaseIds[]=$request['leaseId'];
        if(!is_array($leaseIds)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'租期格式有误');
        }

        $OrderLease= OrderLease::query()->whereIn('id',$leaseIds)->where('status','<>',OrderLease::ORDER_LEASE_STATUS_PAID)
            ->where('order_id',$request['orderId'])
            ->select(
                'id','which_period','status','rent','paid_rent',
            )
            ->get();
        $OrderLease = $OrderLease ? $OrderLease->toArray() : [];
        if(empty($OrderLease)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
        }


        $payAmount=WechatService::getFundFlowOne(trim($request['transaction_id']));
        if(!$payAmount){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'交易单号验证失败');
        }

        if(count($OrderLease)!=count($leaseIds)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'提交的租期不能包含已支付的租期');
        }
        foreach ($OrderLease as $v){
            if($v['status']==1&&!empty($v['pay_time'])){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'该期已支付');
            }
        }



        DB::beginTransaction();
        foreach ($OrderLease as $v){

            $should_pay_amount= bcsub($v['rent'],$v['paid_rent'],2);


            if($payAmount>=$should_pay_amount&&count($OrderLease)>1){
                $payAmount=bcsub((string)$payAmount,$should_pay_amount,2);
            }else{
                $should_pay_amount= $payAmount;
            }

            $add = [
                'order_id'=>$request['orderId'],
                'lease_id'=>$v['id'],
                'sub_remark'=>$request['remark'],
                'amount'=>$should_pay_amount,
                'image_path'=>$request['image_path'],
                'transaction_id'=>$request['transaction_id']??'',
                'create_time'=>time(),
                'admin_id'=>$user['id']
            ];
            $audit_id= (new OrderLeaseAudit)->insertGetId($add);
            if($audit_id){
                if($should_pay_amount>0){
                    if($v['rent']<=bcadd($v['paid_rent'],$should_pay_amount,2)){
                        $leaseSave['trade_no']   = $request['transaction_id'];
                        $leaseSave['out_order_no'] = $request['transaction_id'];
                        $leaseSave['pay_time']  = time();
                        $leaseSave['status']    = OrderLease::ORDER_LEASE_STATUS_PAID;
                        $leaseSave['pay_type'] = OrderLease::LEASE_PAY_TYPE_WECHAT;
                        OrderLease::where('id', $v['id'])->where('order_id',$request['orderId'])->update($leaseSave);
                    }

                    if($should_pay_amount){
                        OrderLease::where('id', $v['id'])->where('order_id',$request['orderId'])->increment('paid_rent',$should_pay_amount);
                    }
                    $res=OrderLeaseAudit::where('lease_id',$v['id'])->where('id',$audit_id)->update(['check_status'=>1,'update_time'=>time()]);

                    if($res){
                        //检测逾期订单状态
                        $status = Order::checkOrderOverdueStatus($order['id']);
                        if ($status) {
                            Order::where(['id' => $order['id']])->update(['status' => $status]);
                        }
                    }else{
                        DB::rollBack();
                        return ReturnMsg(CommonService::HTTP_CODE_FAIL,'更改失败');
                    }
                }
            }else{
                DB::rollBack();
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'更改失败');
            }
        }

        DB::commit();
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'提交申请成功');


    }


    /**
     * 分期部分还款
     */
    public function submitLeasePartial(Request $request){
        if(empty($request['partialAmount'])||empty($request['leaseId'])||empty($request['payType'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
        }

        if(!is_numeric($request['partialAmount'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'金额填写有误');
        }
        $OrderLease= OrderLease::where('id',$request['leaseId'])->where('order_id',$request['orderId'])
            ->select(
                'id','which_period','status','order_id','rent','overdue_amount'
            )
            ->first();
        $OrderLease = $OrderLease ? $OrderLease->toArray() : [];
        if(empty($OrderLease)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
        }
        if($OrderLease['status']==1&&!empty($OrderLease['pay_time'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'该期已支付');
        }

        $order = Order::where(['id'=>$OrderLease['order_id']])->whereIn('status',OrderService::getOrderStatus(OrderService::ORDER_WITHHOLD_OR_PAY))
            ->select('trade_no','seller_id','status','pact_url','sign_status')->first();
        $order = obToArray($order);
        if (!$order){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'待支付订单不存在');
        }
        if ($order['sign_status']!=2||empty($order['pact_url'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请签约合同后获取收款码');
        }
        $order_no=$order['trade_no'];
        $add = [
            'lease_id'=>$request['leaseId'],
            'partial_amount'=>$request['partialAmount'],
            'pay_type'=>$request['payType'],
            'create_time'=>time(),
            'reason'=>$this->users['username'].'发起支付',
            'out_trade_no'=>$order_no.'|'.time(),
        ];
        $partial_amount= OrderLeasePartial::where('lease_id',$request['leaseId'])->where('status',OrderLeasePartial::STATUS_ISPAY)->sum('partial_amount');
        if(($request['partialAmount']+$partial_amount)>bcadd($OrderLease['overdue_amount']+$OrderLease['rent'],2)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请务大于可还金额');
        }
        $res=OrderLeasePartial::insert($add);

        $options = new QROptions([
            'version'    => 4,                             //二维码版本
            'outputType' => QRCode::OUTPUT_IMAGE_JPG,      //生成图片
            'eccLevel'   => QRCode::ECC_L,                 //错误级别
            'scale'=>6,                                   //二维码大小
        ]);
        $qrcode = new QRCode($options);


        if($request['payType']==OrderLeasePartial::PAY_WXPAY){
            $res=WechatService::nativeUnifiedorder($OrderLease['id'],$request['partialAmount'],$OrderLease['which_period'],$add['out_trade_no']);
            if($res['result_code']=='SUCCESS'){
                $paycode=$qrcode->render($res['code_url']);
            }
            $img='img/wxpay.png';
        }

        if($request['payType']==OrderLeasePartial::PAY_ALIPAY){
            $params=[
                'order_no'=>$add['out_trade_no'],
                'order_id'=>$OrderLease['order_id'],
                'lease_id'=>$OrderLease['id'],
                'which_period'=>$OrderLease['which_period'],
                'totalAmount'=>$request['partialAmount'],
            ];
            $res=AlipayService::alipayOrderLeasePay($params);

            if($res['status']){
                $paycode=$qrcode->render($res['data']['qr_code']);
            }
            $img='img/alipay.png';
        }

        $canvas = Image::canvas(450, 550);
        $head = Image::make(public_path($img))
            ->resize(450, 550);

        $canvas->insert($head, 'top-left', 0, 0)
            ->insert($paycode, 'top-left', 98, 238);
//        $canvas->response('data-url', 90);
//        //var_dump($canvas->encode()->getEncoded());
//
//        $paycode=$canvas->encode();
        $paycode=$canvas->response('data-url', 90);
        $paycode=json_encode($paycode);
        $paycode=json_decode($paycode,true);
        if($res){
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'提交申请成功',$paycode['original']);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'更改失败');
        }
    }



    /**
     * 结算价买断
     */
    public function submitOrderBuyOut(Request $request){
//        dd($request);
        if((empty($request['amount'])&&empty($request['reduced_amount']))||empty($request['orderId'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
        }
        $userToken = $request->header("Authorization");
        $user = NewAdmin::where(['token'=>$userToken,'type'=>AuthService::MODEL_ADMIN])->first();
        $user = obToArray($user);

        if(md5($user['mobile'].$request['password']) != $user['password']){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'密码输入错误错误');
        }

        if(!empty($request['reduced_amount'])&&!empty($request['amount'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'优惠金额或买断金额填其一');
        }
        if(empty($request['reduced_amount'])&&empty($request['amount'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'优惠金额或买断金额填其一');
        }

        if(!empty($request['reduced_amount'])&&!is_numeric($request['reduced_amount'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'金额填写有误');
        }
        if(!empty($request['amount'])&&!is_numeric($request['amount'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'金额填写有误');
        }

        if(!empty($request['reduced_amount'])){
            $one=OrderLease::where('order_id',$request['orderId'])->where('status','<>',OrderLease::ORDER_LEASE_STATUS_PAID)->first();
            if($one){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'账单用户未支付完成');
            }
        }


        $order= Order::from('sp_order_2 as o')
            ->where('o.id',$request['orderId'])
            ->leftJoin('sp_order_goods_2 as og','og.order_id','=','o.id')
            ->whereIn('o.status',array_merge(OrderService::getOrderStatus(OrderService::ORDER_WITHHOLD_OR_PAY),['60']))
            ->select('o.id','o.status','o.sign_status','o.pact_url','og.pact_type')
            ->first();
        $order = $order ? $order->toArray() : [];
        if(empty($order)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
        }
        if(!in_array($order['status'],['30','38','39','42','60'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'该状态不支持买断结算');
        }
        if ($order['sign_status']!=2||empty($order['pact_url'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请签约合同后提交');
        }
        $add = [
            'order_id'=>$request['orderId'],
            'amount'=>$request['amount'],
            'reduced_amount'=>$request['reduced_amount'],
            'sub_remark'=>$request['remark'],
            'image_path'=>$request['image_path'],
            'create_time'=>time(),
            'admin_id'=>$user['id']
        ];
        $rent= OrderLease::where('order_id',$request['orderId'])->where('status','<>',1)->sum('rent');
        $overdue_amount= OrderLease::where('order_id',$request['orderId'])->where('status','<>',1)->sum('overdue_amount');

        $orderGood=OrderGoods::where('order_id',$order['id'])->select('id','setmeal_price','pact_type')
            ->first();

        if($orderGood['pact_type']!='2'){
            $total=bcadd($rent+$overdue_amount,$orderGood['setmeal_price'],2);
        }else{
            $total=bcadd($rent,$overdue_amount,2);
        }

//        if($total<$request['amount']&&$order['pact_type']==2){
//            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请务大于剩余租金总额');
//        }
        $res=OrderBuyoutAudit::insert($add);

        if($res){
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'提交申请成功');
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'更改失败');
        }
    }


    /**
     * 分期部分还款备注
     */
    public function submitLeasePartialRemark(Request $request){
        if(empty($request['amount'])||empty($request['leaseId'])||empty($request['orderId'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
        }

        if(!is_numeric($request['amount'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'金额填写有误');
        }
        $OrderLease= OrderLease::where('id',$request['leaseId'])->where('order_id',$request['orderId'])
            ->select(
                'id','which_period','status','order_id','rent','overdue_amount','pay_time'
            )
            ->first();
        $OrderLease = $OrderLease ? $OrderLease->toArray() : [];
        if(empty($OrderLease)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
        }
        if($OrderLease['status']==1&&!empty($OrderLease['pay_time'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'该期已支付');
        }

        $order = Order::where(['id'=>$OrderLease['order_id']])->whereIn('status',OrderService::getOrderStatus(OrderService::ORDER_WITHHOLD_OR_PAY))
            ->select('trade_no','seller_id','status','pact_url','sign_status')->first();
        $order = obToArray($order);
        if (!$order){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'待支付订单不存在');
        }
        if ($order['sign_status']!=2||empty($order['pact_url'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请签约合同后获取收款码');
        }
        $add = [
            'uid'=>$this->users['id'],
            'username'=>$this->users['username'],
            'create_time'=>time(),
            'order_lease_id'=>$request['leaseId'],
            'order_id'=>$request['orderId'],
            'amount'=>$request['amount'],
        ];
        $res=OrderLeasePartRemark::insert($add);
        if($res){
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'提交成功');
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'提交失败');
        }

    }

}
